package com.hjb.toolbardemo.base;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.app_library.utils.LogC;

import java.lang.reflect.Field;

/**
 * 作者 : hjb
 * 时间 : 2016/4/25.
 */
public abstract class BaseFragment extends Fragment implements KeyEvent.Callback {

    /**
     * 根元素
     */
    protected View rootView;
    /**
     * 布局渲染工具
     */
    protected LayoutInflater mInflater;
    protected Context mContext;
    public BaseActivity activity;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mInflater = inflater;
        mContext = inflater.getContext();
        rootView = initRootView();
        activity = (BaseActivity) getActivity();
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setViews();
        initData();
    }

    /**
     * 初始化View,加载布局
     *
     * @return 布局
     */
    public abstract View initRootView();

    /**
     * 填充某View下的某TextView
     *
     * @param rootView TextView的父view
     * @param resId    TextView 的id
     * @param content  TextView 文本内容
     */
    protected void fillTextView(View rootView, int resId, String content) {
        TextView tv = (TextView) rootView.findViewById(resId);
        tv.setText(content);
    }

    /**
     * 解决fragment嵌套问题:No activity
     */
    @Override
    public void onDetach() {
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class
                    .getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);

        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 初始化数据
     */
    public abstract void setViews();

    /**
     * 加载网络数据
     */
    public abstract void initData();

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            getActivity().finish();
        }
        return true;
    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {

        return false;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {

        return false;
    }

    @Override
    public boolean onKeyMultiple(int keyCode, int count, KeyEvent event) {

        return false;
    }

}
